package com.zwp.base.uitls

import android.app.Activity
import android.app.Application
import android.content.ComponentCallbacks
import android.content.res.Configuration

/**
 * Desc: 字节屏幕适配
 *
 * @param size 设计图宽度dp
 */
fun CustomDensity(activity: Activity, application: Application, size: Int) {
    val appDisplayMetrics = application.resources.displayMetrics
    val targetDensity = appDisplayMetrics.widthPixels / size.toFloat()
    val targetDensityDpi = (160 * targetDensity).toInt()

    var appScaledDensity = appDisplayMetrics.scaledDensity

    appDisplayMetrics.apply {
        density = targetDensity
        densityDpi = targetDensityDpi
    }

    application.registerComponentCallbacks(object : ComponentCallbacks {
        override fun onConfigurationChanged(newConfig: Configuration) {
            if (newConfig.fontScale > 0) {
                appScaledDensity = application.resources.displayMetrics.scaledDensity
            }
        }

        override fun onLowMemory() = Unit

    })

    val activityDisplayMetrics = activity.resources.displayMetrics
    activityDisplayMetrics.apply {
        scaledDensity =
            targetDensity * (appScaledDensity / appDisplayMetrics.density)
        density = targetDensity
        densityDpi = targetDensityDpi
    }
}